package com.game.action.gm;

import com.coment.cfg.luban.Tables;
import com.coment.cfg.luban.constant.AIDCFG;
import com.coment.cfg.luban.items.TitleCfg;
import com.coment.game.fight.Attribute;
import com.coment.game.fight.AttributeManagerLogic;
import com.coment.game.fight.Attrs;
import com.coment.po.*;
import com.coment.po.roles.CultivatePanel;
import com.coment.po.roles.Roles;
import com.game.dao.user.account.UserAccountDao;
import com.game.dao.user.roles.RolesDao;
import com.game.dao.user.task.UserTaskInfoDao;
import com.game.logic.fighting.pve.GameTime;
import com.game.logic.items.pet.PetService;
import com.game.logic.items.prop.PropService;
import com.game.logic.items.title.UserTitle;
import com.game.logic.items.title.UserTitleService;
import com.game.logic.ranking.WordRakingService;
import com.game.logic.roles.RolesService;
import com.game.logic.task.UserTaskInfoService;
import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/// 99-GM命令
@Slf4j
@RestController
@RequestMapping("/GM")
public class GameAction {
    @Resource
    private RolesService rolesService;
    @Resource
    private PetService petService;
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private RolesDao rolesDao;
    @Resource
    private UserAccountDao userAccountDao;
    @Resource
    private PropService propService;
    @Resource
    private WordRakingService wordRakingService;

    @Resource
    private RedisTemplate<String, ?> redisTemplate;
    @Autowired
    private UserTitleService userTitleService;
    @Autowired
    private UserTaskInfoDao userTaskInfoDao;
    @Autowired
    private UserTaskInfoService userTaskInfoService;

    /// 获取所有角色
    @GetMapping("/obtainAllRoles")
    public void obtainAllRoles(Integer userInfoId) {
        for (int i = 1; i < Tables.cfg.get_tbcardtalentconfig().getDataList().size() + 1; i++) {
            rolesService.tryObtainRoles(userInfoId, i);
        }
    }

    /// 获取指定角色
    @GetMapping("/obtainRole")
    public Roles obtainRole(Integer userInfoId, Integer cardId) {
        Roles roles = rolesService.tryObtainRoles(userInfoId, cardId);
        log.debug("获取角色 {}", Attribute.getLogInfo(roles.rolePanel.getAttribute()));
        return roles;
    }

    /// 指定玩家角色发放经验 - 如果没有将获取角色
    @GetMapping("/obtainRoleExp")
    public Roles obtainRoleExp(Integer userInfoId, Integer cardId, double exp) {
        Roles roles = rolesDao.searchByUserInfoIdAndCardId(userInfoId, cardId);
        if (roles == null) {
            roles = rolesService.tryObtainRoles(userInfoId, cardId);
        }
        roles.rolePanel.cultivatePanel.base.merge(AIDCFG.exp, exp, Double::sum);
        this.rolesDao.save(roles);
        return roles;
    }


    /// 获取所有宠物
    @GetMapping("/obtainAllPets")
    public List<UserPet> obtainAllPets(Integer userInfoId) {
        log.info("obtainAllPets");
        List<UserPet> pets = new ArrayList<>();
        for (int petId = 1; petId < Tables.cfg.get_tbpetcfg().getDataList().size() + 1; petId++) {
            pets.add(petService.tryObtainPet(userInfoId, petId));
        }
        return pets;
    }

    /// 获取指定宠物
    @GetMapping("/obtainPet")
    public UserPet obtainPet(Integer userInfoId, int petId) {
        return petService.tryObtainPet(userInfoId, petId);
    }


    /// 重新加载所有配置数据
    @GetMapping("/reloadAll")
    public void reloadAll() {
        try {
            Tables.reloadAll();
            AttributeManagerLogic.loadingCfg();
        } catch (Exception e) {
            log.error("重新加载配置数据失败", e);
        }
    }

    /// 重置养成数据
    @GetMapping("/resetCultivationData")
    public void resetCultivationData() {
        mongoTemplate.dropCollection(UserPet.class);
        mongoTemplate.dropCollection(Roles.class);
        mongoTemplate.dropCollection(Game.class);
        mongoTemplate.dropCollection(UserInfo.class);
        mongoTemplate.dropCollection(UserPlayInfo.class);
        GameTime.activeRooms.clear();
    }

    /// 重置服务
    @GetMapping("/reset")
    public void reset() {
        for (Class<?> aClass : List.of(
                AnchorInfo.class,
                AttrsGlobal.class,
                Game.class,
                Roles.class,
                ServerInfo.class,
                UserAccount.class,
                UserInfo.class,
                UserPet.class,
                UserPlayInfo.class,
                UserProp.class,
                UserRolesProp.class,
                UserTaskInfo.class,
                UserTitle.class
        )) {
            mongoTemplate.dropCollection(aClass);
        }

        // redis直接清空
        if (redisTemplate.getConnectionFactory() != null) {
            redisTemplate.getConnectionFactory().getConnection().serverCommands().flushAll();
        }
    }


    /// 发钱
    @GetMapping("/sendMoney")
    public Double[] sendMoney(
            Integer userInfoId,
            double[] money
    ) {
        UserAccount byUserInfoId = userAccountDao.findByUserInfoIdOrCreate(userInfoId);
        int ml = money.length;
        // 扩容判定 - 不动原来数据
        if (byUserInfoId.currency.length < ml) {
            byUserInfoId.currency = Arrays.copyOf(byUserInfoId.currency, ml);
        }
        for (int i = 0; i < ml; i++) {
            // 设置初始值：如果为null则初始化为0.0
            if (byUserInfoId.currency[i] == null) {
                byUserInfoId.currency[i] = 0.0;
            }
            byUserInfoId.currency[i] += money[i];
        }
        userAccountDao.save(byUserInfoId);
        return byUserInfoId.currency;
    }

    /// 发放道具
    @GetMapping("/distributeProps")
    public UserProp distributeProps(Integer userInfoId, int propId) {
        return propService.obtainOrUpgrade(userInfoId, propId);
    }


    /// 发放指定类型道具
    @GetMapping("/distributePropsByGroup")
    public List<UserProp> distributePropsByGroup(Integer userInfoId, Integer... groups) {
        return propService.obtainOrUpgrade(userInfoId, groups);
    }


    /// 手动刷新世界榜单
    @GetMapping("/worldFightingCapacityRaking")
    public void worldFightingCapacityRaking() {
        wordRakingService.worldFightingCapacityRaking();
    }


    /// gm获取所有称号
    @GetMapping("/obtainTitle")
    public void obtainTitle(Integer userInfoId) {
        for (TitleCfg titleCfg : Tables.cfg.get_tbtitlecfg().get_dataList()) {
            userTitleService.obtain(userInfoId, titleCfg.id);
        }
    }


    @Getter
    @Setter
    public static class HandlerUserTaskRequest {
        /// 用户id
        Integer userInfoId;
        /// 任务id : 完成次数
        Map<Integer, Integer> idAndLv;
    }

    /// 处理用户任务
    @PostMapping("/handlerUserTask")
    public List<UserTaskInfo> handlerUserTask(@RequestBody HandlerUserTaskRequest request) {
        Integer userInfoId = request.userInfoId;

        request.idAndLv.forEach((taskId, num) -> Optional.ofNullable(Tables.cfg.get_tbtaskcfg().get(taskId)).ifPresent(cfg -> {
            UserTaskInfo taskInfo = userTaskInfoDao.findUserTaskInfoByUserInfoIdAndTaskId(userInfoId, taskId);
            taskInfo.setCompletionCount(num);
            userTaskInfoDao.save(taskInfo);
            int canClaimed = num - taskInfo.getQuantityClaimed();
            for (int i = 0; i < canClaimed; i++) {
                userTaskInfoService.obtainReward(userInfoId, taskId);
            }
        }));
        return userTaskInfoDao.findByUserInfoId(userInfoId);
    }

    @GetMapping("obtainAttrsLog")
    public String obtainAttrsLog(String rolesId) {
        Roles byIdMust = rolesDao.findByIdMust(rolesId);
        CultivatePanel cultivatePanel = byIdMust.getRolePanel().getCultivatePanel();

        Attrs value = cultivatePanel.getValue();
        StringBuilder logInfo = Attribute.getLogInfo(value);
        return Attribute.eqLog(log, value);
    }

}
